package com.tsfyun.common.base.util;

import com.tsfyun.common.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @Description:
 * @since Created in 2020/4/30 09:38
 */
@Slf4j
public class Base64Util {

    /**
     * 本地图片转base64方法
     * @param filaName （包含路径）
     * @return
     */
    public static String encodeBase64(String filaName) {
        InputStream in;
        byte[] data;
        File file = new File(filaName);
        if(!file.exists()) {
            log.error("文件不存在，文件全路径【{}】",filaName);
            throw new ServiceException("文件不存在");
        }
        //读取图片字节数组
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            throw new ServiceException("文件信息读取异常");
        }
        return new BASE64Encoder().encode(data);
    }


}
